--- 大连道胜T3-1 modbus 9600,N,8,1
module(..., package.seeall)

local logtag = "dldsT3_1"
local cid, uid = 3, 3 -- 默认用3通道
local dtu, udtu = {}, {} -- 配置文件
local read_ins = '010305A6000224E4' --顺时，  float,回复数据:010304851F4145135A 12.34
local read_dat = '010305AC000204E6' --净累积，float,回复数据:01030487DD4145B31E 12.34567
local read_bat = '010305AE0002A526' --水表电池电量，float,回复数据:010304 08004068 C87D //值为40 68 80 00  float：3.632813

local meter_ins ,meter_val ,meter_bat
        
function setDtu(dtup, udtup)
    dtu, udtu = dtup, udtup
    -- 如果设置是本协议
    if udtu and tonumber(udtu.dtype) == 3 then sys.taskInit(init) end
end
local function process(data, status)
    if #data > 8 then
        local _, val = pack.unpack(data:sub(6, 7) .. data:sub(4, 5), ">f")
        if status == 2 then
            meter_ins = string.format("%.2f", val)
            lcd.LCD_DATA[3] = '瞬时流量:' .. (meter_ins or "NULL")
        elseif status == 3  then
            meter_val = string.format("%.2f", val)
            lcd.LCD_DATA[3] = '累计流量:' .. (meter_val or "NULL")
        elseif status == 1  then
            meter_bat = string.format("%.2f", val)
            usrdata.update({meter_val, meter_ins, meter_bat})
            lcd.LCD_DATA[3] = '水表电压:' .. (meter_bat or "NULL")
        end
    end
end
local function read_meter_ins()
    sys.publish("UART_SENT_RDY_" .. uid, uid, read_ins:fromHex())
end
local function read_meter_val()
    sys.publish("UART_SENT_RDY_" .. uid, uid, read_dat:fromHex())
end
local function read_meter_bat()
    sys.publish("UART_SENT_RDY_" .. uid, uid, read_bat:fromHex())
end
function init()
    power.openBoost()
    sys.wait(200)
    local status = 1
    while true do
        if status == 1 then
            status = 2
            read_meter_ins()
        elseif status == 2 then
            status = 3
            read_meter_val()
        elseif status == 3 then
            status = 1
            read_meter_bat()
        end
        log.warn(logtag, "间隔10秒等待串口数据,UART" .. uid)
        -- 等待串口回复
        local result, d = sys.waitUntil('UART_READ_DONE_NEXT_' .. uid, 5000)
        if result then
            if (d) then
                -- log.warn(logtag, '收到串口' .. uid .. '回复数据:', d)
                process(d, status)
            end
            sys.wait(2*1000) -- 5秒切换读取
        else
            lcd.LCD_DATA[3] = string.format("U%dD%d NOREADY",uid,udtu.dtype)
        end
    end
end
